import { useEffect, useState } from 'react';
import { FilterSidebar } from '../components/FilterSidebar';
import { ProductCard } from '../components/ProductCard';
import { Pagination } from '../components/Pagination';
import { Filter, X } from 'lucide-react';
import { setPageTitle } from '../lib/utils';

export function Skincare() {
  const [currentPage, setCurrentPage] = useState(1);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState<Record<string, string[]>>({});
  const [filteredProducts, setFilteredProducts] = useState<any[]>([]);
  const productsPerPage = 9;
  // Mock skincare products data
  const products = [{
    id: 'sk-001',
    title: 'Hydrating Rose Facial Toner',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1608248597279-f99d160bfcbc?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.8,
    reviewCount: 124,
    price: 28.0,
    category: 'Skincare',
    type: 'toner',
    concern: ['hydration', 'balance'],
    skinType: ['normal', 'dry']
  }, {
    id: 'sk-002',
    title: 'Vitamin C Brightening Serum',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1576426863848-c21f53c60b19?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 89,
    price: 52.0,
    category: 'Skincare',
    type: 'serum',
    concern: ['brightening', 'anti-aging'],
    skinType: ['all']
  }, {
    id: 'sk-003',
    title: 'Overnight Hydration Mask',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.9,
    reviewCount: 76,
    price: 38.0,
    originalPrice: 48.0,
    category: 'Skincare',
    type: 'mask',
    concern: ['hydration', 'repair'],
    skinType: ['dry', 'normal']
  }, {
    id: 'sk-004',
    title: 'Green Tea Cleansing Oil',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1595348020949-87cdfbb44174?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.6,
    reviewCount: 53,
    price: 34.0,
    category: 'Skincare',
    type: 'cleanser',
    concern: ['cleansing', 'balance'],
    skinType: ['combination', 'oily']
  }, {
    id: 'sk-005',
    title: 'Hyaluronic Acid Moisture Boost',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1567721913486-6585f069b332?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 112,
    price: 48.0,
    category: 'Skincare',
    type: 'serum',
    concern: ['hydration', 'plumping'],
    skinType: ['all']
  }, {
    id: 'sk-006',
    title: 'Nourishing Face Oil',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1598662972299-5408ddb8a3dc?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.8,
    reviewCount: 67,
    price: 56.0,
    category: 'Skincare',
    type: 'oil',
    concern: ['nourishing', 'repair'],
    skinType: ['dry', 'normal']
  }, {
    id: 'sk-007',
    title: 'Gentle Exfoliating Scrub',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1556228578-0d85b1a4d571?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.5,
    reviewCount: 42,
    price: 32.0,
    category: 'Skincare',
    type: 'exfoliator',
    concern: ['exfoliation', 'brightening'],
    skinType: ['all']
  }, {
    id: 'sk-008',
    title: 'Calming Aloe Gel Moisturizer',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1601049541289-9b1b7bbbfe19?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.4,
    reviewCount: 38,
    price: 42.0,
    category: 'Skincare',
    type: 'moisturizer',
    concern: ['calming', 'hydration'],
    skinType: ['sensitive', 'normal']
  }, {
    id: 'sk-009',
    title: 'Retinol Night Repair Cream',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1625772452859-1c03d5bf1137?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.9,
    reviewCount: 95,
    price: 68.0,
    originalPrice: 78.0,
    category: 'Skincare',
    type: 'moisturizer',
    concern: ['anti-aging', 'repair'],
    skinType: ['normal', 'dry']
  }, {
    id: 'sk-010',
    title: 'Purifying Clay Mask',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1608248543803-ba4f8c70ae0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.6,
    reviewCount: 57,
    price: 36.0,
    category: 'Skincare',
    type: 'mask',
    concern: ['purifying', 'detox'],
    skinType: ['combination', 'oily']
  }, {
    id: 'sk-011',
    title: 'Brightening Eye Cream',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1614859073991-1e5c2093b4f7?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 48,
    price: 46.0,
    category: 'Skincare',
    type: 'eye care',
    concern: ['brightening', 'anti-aging'],
    skinType: ['all']
  }, {
    id: 'sk-012',
    title: 'Soothing Rosewater Mist',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1608248543803-ba4f8c70ae0b?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.5,
    reviewCount: 63,
    price: 24.0,
    category: 'Skincare',
    type: 'mist',
    concern: ['soothing', 'hydration'],
    skinType: ['all', 'sensitive']
  }];
  // Filter categories
  const filterCategories = [{
    name: 'Product Type',
    options: [{
      id: 'cleanser',
      label: 'Cleanser'
    }, {
      id: 'toner',
      label: 'Toner'
    }, {
      id: 'serum',
      label: 'Serum'
    }, {
      id: 'moisturizer',
      label: 'Moisturizer'
    }, {
      id: 'mask',
      label: 'Mask'
    }, {
      id: 'oil',
      label: 'Oil'
    }, {
      id: 'exfoliator',
      label: 'Exfoliator'
    }, {
      id: 'eye care',
      label: 'Eye Care'
    }, {
      id: 'mist',
      label: 'Mist'
    }]
  }, {
    name: 'Skin Concern',
    options: [{
      id: 'hydration',
      label: 'Hydration'
    }, {
      id: 'brightening',
      label: 'Brightening'
    }, {
      id: 'anti-aging',
      label: 'Anti-Aging'
    }, {
      id: 'balance',
      label: 'Balance'
    }, {
      id: 'repair',
      label: 'Repair'
    }, {
      id: 'cleansing',
      label: 'Cleansing'
    }, {
      id: 'plumping',
      label: 'Plumping'
    }, {
      id: 'nourishing',
      label: 'Nourishing'
    }, {
      id: 'exfoliation',
      label: 'Exfoliation'
    }, {
      id: 'calming',
      label: 'Calming'
    }, {
      id: 'purifying',
      label: 'Purifying'
    }, {
      id: 'detox',
      label: 'Detox'
    }, {
      id: 'soothing',
      label: 'Soothing'
    }]
  }, {
    name: 'Skin Type',
    options: [{
      id: 'all',
      label: 'All Skin Types'
    }, {
      id: 'dry',
      label: 'Dry'
    }, {
      id: 'oily',
      label: 'Oily'
    }, {
      id: 'combination',
      label: 'Combination'
    }, {
      id: 'normal',
      label: 'Normal'
    }, {
      id: 'sensitive',
      label: 'Sensitive'
    }]
  }, {
    name: 'Brand',
    options: [{
      id: 'Pure Bloom',
      label: 'Pure Bloom'
    }, {
      id: 'Glow Theory',
      label: 'Glow Theory'
    }, {
      id: 'Ritual Beauty',
      label: 'Ritual Beauty'
    }]
  }];

  // Set page title
  useEffect(() => {
    setPageTitle('Skincare');
  }, []);

  // Apply filters
  useEffect(() => {
    let result = [...products];
    // Apply filters for each category
    Object.entries(selectedFilters).forEach(([category, selectedOptions]) => {
      if (selectedOptions.length > 0) {
        result = result.filter(product => {
          if (category === 'Product Type') {
            return selectedOptions.includes(product.type);
          } else if (category === 'Skin Concern') {
            return product.concern.some(concern => selectedOptions.includes(concern));
          } else if (category === 'Skin Type') {
            return product.skinType.some(type => selectedOptions.includes(type));
          } else if (category === 'Brand') {
            return selectedOptions.includes(product.brand);
          }
          return true;
        });
      }
    });
    setFilteredProducts(result);
    setCurrentPage(1); // Reset to first page when filters change
  }, [selectedFilters]);
  // Initialize filtered products
  useEffect(() => {
    setFilteredProducts(products);
  }, []);
  const handleFilterChange = (category: string, optionId: string) => {
    setSelectedFilters(prev => {
      const prevSelected = prev[category] || [];
      // If already selected, remove it
      if (prevSelected.includes(optionId)) {
        const updated = prevSelected.filter(id => id !== optionId);
        return {
          ...prev,
          [category]: updated
        };
      }
      // Otherwise add it
      return {
        ...prev,
        [category]: [...prevSelected, optionId]
      };
    });
  };
  const clearFilters = () => {
    setSelectedFilters({});
  };
  // Calculate pagination
  const totalPages = Math.ceil(filteredProducts.length / productsPerPage);
  const indexOfLastProduct = currentPage * productsPerPage;
  const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
  const currentProducts = filteredProducts.slice(indexOfFirstProduct, indexOfLastProduct);
  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
    window.scrollTo(0, 0);
  };
  return <div className="max-w-7xl mx-auto px-4 md:px-8 lg:px-12 py-12">
      <div className="mb-8">
        <h1 className="font-serif text-3xl md:text-4xl text-[#4a4a4a] mb-4">
          Skincare
        </h1>
        <p className="text-sm md:text-base max-w-3xl">
          Discover our curated collection of gentle, effective skincare products
          designed to enhance your natural beauty. From hydrating serums to
          nourishing masks, find the perfect addition to your daily ritual.
        </p>
      </div>
      {/* Mobile filter button */}
      <div className="md:hidden mb-6">
        <button onClick={() => setShowFilters(true)} className="w-full flex items-center justify-center space-x-2 bg-white border border-[#e8e5e0] py-3 rounded-md">
          <Filter size={18} />
          <span>Filter Products</span>
        </button>
      </div>
      {/* Mobile filter drawer */}
      {showFilters && <div className="md:hidden">
          <FilterSidebar categories={filterCategories} selectedFilters={selectedFilters} onFilterChange={handleFilterChange} onClearFilters={clearFilters} isMobile={true} onClose={() => setShowFilters(false)} />
        </div>}
      <div className="flex flex-col md:flex-row gap-8">
        {/* Desktop Sidebar */}
        <div className="hidden md:block w-64 flex-shrink-0">
          <FilterSidebar categories={filterCategories} selectedFilters={selectedFilters} onFilterChange={handleFilterChange} onClearFilters={clearFilters} />
        </div>
        {/* Product Grid */}
        <div className="flex-1">
          {/* Active filters */}
          {Object.entries(selectedFilters).some(([_, values]) => values.length > 0) && <div className="mb-6 flex flex-wrap gap-2 items-center">
              <span className="text-sm font-medium">Active Filters:</span>
              {Object.entries(selectedFilters).map(([category, values]) => values.map(value => {
            // Find the label for this value
            const filterCategory = filterCategories.find(c => c.name === category);
            const option = filterCategory?.options.find(o => o.id === value);
            return <div key={`${category}-${value}`} className="flex items-center bg-[#f3f0eb] px-3 py-1 rounded-full text-sm">
                      <span>{option?.label || value}</span>
                      <button onClick={() => handleFilterChange(category, value)} className="ml-2 text-[#4a4a4a]" aria-label={`Remove ${option?.label || value} filter`}>
                        <X size={14} />
                      </button>
                    </div>;
          }))}
              <button onClick={clearFilters} className="text-sm text-[#4a6b60] hover:underline">
                Clear All
              </button>
            </div>}
          {/* Results count and sort */}
          <div className="flex justify-between items-center mb-6">
            <p className="text-sm">
              Showing {indexOfFirstProduct + 1}-
              {Math.min(indexOfLastProduct, filteredProducts.length)} of{' '}
              {filteredProducts.length} products
            </p>
            <div className="flex items-center">
              <label htmlFor="sort" className="text-sm mr-2">
                Sort by:
              </label>
              <select id="sort" className="text-sm border border-[#e8e5e0] rounded-md px-2 py-1 focus:outline-none focus:border-[#4a6b60]">
                <option value="featured">Featured</option>
                <option value="newest">Newest</option>
                <option value="price-low">Price: Low to High</option>
                <option value="price-high">Price: High to Low</option>
                <option value="rating">Top Rated</option>
              </select>
            </div>
          </div>
          {/* Products grid */}
          {currentProducts.length > 0 ? <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {currentProducts.map(product => <ProductCard key={product.id} id={product.id} title={product.title} brand={product.brand} image={product.image} rating={product.rating} reviewCount={product.reviewCount} price={product.price} originalPrice={product.originalPrice} category={product.category} />)}
            </div> : <div className="text-center py-12">
              <p className="text-lg font-serif mb-2">No products found</p>
              <p className="text-sm text-gray-500 mb-6">
                Try adjusting your filters to find what you're looking for.
              </p>
              <button onClick={clearFilters} className="bg-[#4a6b60] hover:bg-[#3d5a50] text-white px-6 py-3 rounded-md transition-colors">
                Clear All Filters
              </button>
            </div>}
          {/* Pagination */}
          {filteredProducts.length > productsPerPage && <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} />}
        </div>
      </div>
    </div>;
}